package b3.model
{
	import b3.config.*;
	import b3.net.*;
	import b3.util.*;
	import b3.util.json.*;
	import b3.widget.basic.*;
	
	import flash.events.*;
	import flash.external.*;
	import flash.net.*;
	
	public class Player extends Model
	{	
		public var userId:int;
		
		public var historyMaxPopulation:int;
		
		public var name:String;
		//玩家头像
		public var figureurl:String;
		//玩家本人的QQ ID
		public var openId:String;
		//是否黄钻
		public var is_yellow_vip:Boolean;
		//是否年费黄钻
		public var is_yellow_year_vip:Boolean;
		//黄钻等级
		public var yellow_vip_level:int; 
		//是否领取了黄钻新手礼包
		public var fetchNewPlayerGift:Boolean;
		//是否领取了黄钻今日礼包
		public var fetchDailyGift:Boolean;
		//是否领取了国庆今日礼包
		public var fetchNationalGift:Boolean;
		public var type:int;
		
		public var townModel:TownModel;
		
		public var packageModel:PackageModel;
		//状态集合
		public var stateModel:StateModel;
		
		public var friendList:FriendList;
		
		public var taskList:TaskList;
		
		public var mails:Array;
		
		public var nextTaskId:int;
		
		public var logonAwards:Array;
		
		public var logonDayCount:int;
		//最大体力
		public var vitalityMax:int;
		//体力为空的开始时间
		public var vitalityZeroTime:int;
		//占领者
		public var occupantId:int;
		//占领名字
		public var occupantName:String;
		//社交信息
		public var socialInfos:Array;
		//是否有新社交消息
		public var hasNewSocialInfoFlag:Boolean;
		
		public function Player(userId:int)
		{
			this.userId = userId;
			friendList = new FriendList();
			townModel = new TownModel();
			townModel.ownerId = userId;
			packageModel = new PackageModel();
			packageModel.ownerId = userId;
			stateModel = new StateModel(userId);
			taskList = new TaskList();
			townModel.addEventListener(ModelEvent.REFRESH_BUILDING, onBuildingChange);
			townModel.addEventListener(ModelEvent.ADD_BUILDING, onBuildingChange);
			townModel.addEventListener(ModelEvent.REMOVE_BUILDING, onBuildingChange);
			townModel.addEventListener(ModelEvent.ATTACK_BUILDING, onBuildingChange);
		}
		
		/**
		 * 响应建筑变化，异步更新人口
		 */
		private function onBuildingChange(event:ModelEvent):void
		{
			if (event.data != null && event.data["buildingInfo"] != null)
			{
				var sectionIndex:int = event.data["buildingInfo"]["sectionIndex"];
				//同步人口（会更新玩家本人包裹和个人信息）
				PlayerManager.getInstance().syncPopulation(userId, sectionIndex, true);
			}
		}
		
		public function load():void
		{
			loadPlayerInfo(true);
			townModel.loadBuildings(true);
		}
		
		public function loadPlayerInfo(force:Boolean = false):void
		{
			var serverRequest:ServerRequest = new ServerRequest(ServerEvent.LOAD_PLAYER_INFO, {userId:userId});
			serverRequest.setHandleFunc(handleLoadPlayerInfo);
			serverRequest.post(true);
		}
		
		public function handleLoadPlayerInfo(data:Object):void
		{
			this.loadbyObject(data);
			this.dispatchEvent(new ModelEvent(ModelEvent.REFRESH));
		}
		
		//获取社交信息
		public function getSocialInfo(force:Boolean):void
		{
			var serverRequest:ServerRequest = new ServerRequest(ServerEvent.GET_SOCIAL_INFO, {ownerId: userId});
			serverRequest.setHandleFunc(handleGetSocialInfo);
			serverRequest.post(force);
		}

		//处理社交信息返回
		private function handleGetSocialInfo(data:Object):void
		{
			hasNewSocialInfoFlag = false;
			if (data["socialInfo"] != null)
			{
				socialInfos = new Array();
				for (var str:String in data["socialInfo"])
				{			
					var socailModel:SocialModel = new SocialModel();
					socailModel.loadbyObject(data["socialInfo"][str]);
					if (!socailModel.viewed)
					{
						hasNewSocialInfoFlag = true;
					}
					socialInfos.push(socailModel);
				}
			}
			var event:ModelEvent = new ModelEvent(ModelEvent.GET_SOCIAL_INFO);
			dispatchEvent(event);
		}
		
		public function setSocialInfoViewed():void
		{
			var serverRequest:ServerRequest = new ServerRequest(ServerEvent.SET_SOCIAL_MESSAGE_VIEWED);
			serverRequest.setHandleFunc(handleSetSocialInfoViewed);
			serverRequest.post();
		}
		
		private function handleSetSocialInfoViewed(data:Object):void
		{
			for (var i:int = 0; i < socialInfos.length; i++)
			{
				var socialInfo:SocialModel = socialInfos[i];
				socialInfo.viewed = true;
			}
			this.hasNewSocialInfoFlag = false;
			dispatchEvent(new ModelEvent(ModelEvent.SET_SOCIAL_MESSAGE_VIEWED));
		}

		public function loadMail(force:Boolean):void
		{
			var serverRequest:ServerRequest = new ServerRequest(ServerEvent.GET_MAIL, {toId:userId});
			serverRequest.setHandleFunc(handleLoadMail);
			serverRequest.post(force);
		}
		
		public function handleLoadMail(data:Object):void
		{
			mails = new Array();
			for(var str:String in data)
			{
				var mail:MailModel = new MailModel();
				mail.loadbyObject(data[str]);
				mails.push(mail);
			}
			dispatchEvent(new ModelEvent(ModelEvent.LOAD_MAIL_COMPLETE));
		}
		
		public function maxRoofType(buildingIndex:int):int
		{
			var value:int;
			var buildingConfig:BuildingConfig = Config.buildingConfigs[buildingIndex];
			if (buildingConfig.type == BuildingConfig.WEAPON)
				value = packageModel.getObjectNum(ObjConfig.DARK);
			else if (buildingConfig.type == BuildingConfig.GREEN)
				value = packageModel.getObjectNum(ObjConfig.LIGHT);
			else
				value = historyMaxPopulation;
			var roofType:int = buildingConfig.roofUnlockPopulation.length > 0 ? -1 : 2; 
			for (var j:int = 0, len:int = buildingConfig.roofUnlockPopulation.length; j < len; j++)
			{
				if (value >= buildingConfig.roofUnlockPopulation[j])
				{
					roofType = j;
				}
			}
			return roofType;
		}
		
		public function maxUpgrade(buildingIndex:int):int
		{
			var upgrade:int = 0;
			var value:int;
			var buildingConfig:BuildingConfig = Config.buildingConfigs[buildingIndex];
			if (buildingConfig.type == BuildingConfig.WEAPON)
				value = packageModel.getObjectNum(ObjConfig.DARK);
			else if (buildingConfig.type == BuildingConfig.GREEN)
				value = packageModel.getObjectNum(ObjConfig.LIGHT);
			else
				value = historyMaxPopulation;
			for (var j:int = 0, len:int = buildingConfig.upgradeUnlockPopulation.length; j < len; j++)
			{
				if (value >= buildingConfig.upgradeUnlockPopulation[j])
				{
					upgrade = j + 1;
				}
			}
			return upgrade;
		}
		
		public function maxHeight(buildingIndex:int):int
		{
			var buildingConfig:BuildingConfig = Config.buildingConfigs[buildingIndex];
			return buildingConfig.height + maxUpgrade(buildingIndex) * 2;
		}
		
		public function get vitality():int
		{
			var v:int = (ServerRequest.currentSeconds() - vitalityZeroTime) / 120;
			if (v < 0)
				v = 0;
			else if (v > vitalityMax)
				v = vitalityMax;
			return v;
		}
		
		/**
		 * 对当前玩家的相关游戏信息进行检查，包括检查出其中的有价值信息 （金钱信息、状态信息以及许可证信息）
		 * */
		public function checkAndBuild(obj:Obj = null):void
		{
			var serverRequest:ServerRequest = new ServerRequest(ServerEvent.CHECK_AND_BUILD, {obj: obj});
			serverRequest.setHandleFunc(handleCheckAndBuild);
			serverRequest.post(true);
		}
		
		/**
		 * 处理相关的信息并且进入建造状态
		 */
		public function handleCheckAndBuild( data:Object ):void
		{
			var modelEvent:ModelEvent = new ModelEvent(ModelEvent.CHECK_AND_BUILD_COMPLETE);
		 	modelEvent.data = data;
		 	if (data['err'] == 0)
		 	{
			 	//更新新的状态
			 	this.stateModel.handleLoadStates(data['state']);
			 	this.packageModel.handleLoadObjects(data['package']);
			}
		 	dispatchEvent(modelEvent);
		}
		
		//黄钻每日礼物领取
		public function fetchVipDailyPresent():void
		{
			var serverRequest:ServerRequest = new ServerRequest(ServerEvent.FETCH_VIP_DAILY_PRESENT, {is_yellow_vip: is_yellow_vip, 
				is_yellow_year_vip: is_yellow_year_vip, yellow_vip_level: yellow_vip_level});
			serverRequest.setHandleFunc(handleFetchVipDailyPresent);
			serverRequest.post();
		}
		
		private function handleFetchVipDailyPresent(data:Object):void
		{
		 	this.fetchDailyGift = true;
			if (data['err'] == 0)
			{
			 	this.packageModel.handleLoadObjects(data['package']);
			}
			var event:ModelEvent = new ModelEvent(ModelEvent.FETCH_VIP_DAILY_PRESENT);
		 	event.data = data;
		 	dispatchEvent(event);
		}
		
		//获取黄钻新手礼包
		public function fetchNewPlayerPresent():void
		{
			var serverRequest:ServerRequest = new ServerRequest(ServerEvent.FETCH_VIP_NEW_PRESENT, {is_yellow_vip: is_yellow_vip, is_yellow_year_vip: is_yellow_year_vip});
			serverRequest.setHandleFunc(handleFetchNewPlayerPresent);
			serverRequest.post();
		}
		
		private function handleFetchNewPlayerPresent(data:Object):void
		{
		 	this.fetchNewPlayerGift = true;
			if (data['err'] == 0)
			{
			 	this.packageModel.handleLoadObjects(data['package']);
			}
			var event:ModelEvent = new ModelEvent(ModelEvent.FETCH_NEW_PLAYER_PRESENT);
		 	event.data = data;
		 	dispatchEvent(event);
		}
		
		//国庆每日礼物领取
		public function fetchNationalDailyPresent():void
		{
			var serverRequest:ServerRequest = new ServerRequest(ServerEvent.FETCH_NATIONAL_DAILY_PRESENT);
			serverRequest.setHandleFunc(handleFetchNationalDailyPresent);
			serverRequest.post();
		}
		
		private function handleFetchNationalDailyPresent(data:Object):void
		{
		 	this.fetchNationalGift = true;
			if (data['err'] == 0)
			{
			 	this.packageModel.handleLoadObjects(data['package']);
			}
			var event:ModelEvent = new ModelEvent(ModelEvent.FETCH_NATIONAL_DAILY_PRESENT);
		 	event.data = data;
		 	dispatchEvent(event);
		}
		
	}
}